import os
import hashlib
from datetime import datetime
from typing import List, Optional
from dataclasses import dataclass, field

@dataclass
class Page:
    """漫画页面模型"""
    id: str
    chapter_id: str
    page_number: int
    image_path: str
    image_url: str = ""
    width: int = 0
    height: int = 0
    file_size: int = 0
    
    def __post_init__(self):
        """初始化后处理"""
        if not self.id:
            # 基于文件路径生成唯一ID
            self.id = hashlib.md5(self.image_path.encode()).hexdigest()
        
        if os.path.exists(self.image_path):
            self.file_size = os.path.getsize(self.image_path)
    
    def to_dict(self) -> dict:
        """转换为字典"""
        return {
            'id': self.id,
            'chapter_id': self.chapter_id,
            'page_number': self.page_number,
            'image_path': self.image_path,
            'image_url': self.image_url,
            'width': self.width,
            'height': self.height,
            'file_size': self.file_size
        }

@dataclass
class Chapter:
    """漫画章节模型"""
    id: str
    comic_id: str
    title: str
    path: str
    page_count: int = 0
    pages: List[Page] = field(default_factory=list)
    created_at: datetime = field(default_factory=datetime.now)
    updated_at: datetime = field(default_factory=datetime.now)
    
    def __post_init__(self):
        """初始化后处理"""
        if not self.id:
            # 基于路径生成唯一ID
            self.id = hashlib.md5(self.path.encode()).hexdigest()
        
        # 更新页面数量
        self.page_count = len(self.pages)
    
    def add_page(self, page: Page):
        """添加页面"""
        page.chapter_id = self.id
        self.pages.append(page)
        self.page_count = len(self.pages)
        self.updated_at = datetime.now()
    
    def get_page(self, page_number: int) -> Optional[Page]:
        """获取指定页面"""
        for page in self.pages:
            if page.page_number == page_number:
                return page
        return None
    
    def get_next_page(self, current_page: int) -> Optional[Page]:
        """获取下一页"""
        return self.get_page(current_page + 1)
    
    def get_prev_page(self, current_page: int) -> Optional[Page]:
        """获取上一页"""
        return self.get_page(current_page - 1)
    
    def to_dict(self) -> dict:
        """转换为字典"""
        return {
            'id': self.id,
            'comic_id': self.comic_id,
            'title': self.title,
            'path': self.path,
            'page_count': self.page_count,
            'pages': [page.to_dict() for page in self.pages],
            'created_at': self.created_at.isoformat() if self.created_at else None,
            'updated_at': self.updated_at.isoformat() if self.updated_at else None
        }

@dataclass
class Comic:
    """漫画模型"""
    id: str
    title: str
    path: str
    cover_image: str = ""
    chapters: List[Chapter] = field(default_factory=list)
    created_at: datetime = field(default_factory=datetime.now)
    updated_at: datetime = field(default_factory=datetime.now)
    total_chapters: int = 0
    total_pages: int = 0
    
    def __post_init__(self):
        """初始化后处理"""
        if not self.id:
            # 基于路径生成唯一ID
            self.id = hashlib.md5(self.path.encode()).hexdigest()
        
        # 更新章节和页面统计
        self.update_stats()
    
    def add_chapter(self, chapter: Chapter):
        """添加章节"""
        chapter.comic_id = self.id
        self.chapters.append(chapter)
        self.update_stats()
        self.updated_at = datetime.now()
    
    def get_chapter(self, chapter_id: str) -> Optional[Chapter]:
        """获取指定章节"""
        for chapter in self.chapters:
            if chapter.id == chapter_id:
                return chapter
        return None
    
    def get_chapter_by_index(self, index: int) -> Optional[Chapter]:
        """根据索引获取章节"""
        if 0 <= index < len(self.chapters):
            return self.chapters[index]
        return None
    
    def get_first_page(self) -> Optional[Page]:
        """获取第一页"""
        if self.chapters and self.chapters[0].pages:
            return self.chapters[0].pages[0]
        return None
    
    def get_cover_image(self) -> str:
        """获取封面图片"""
        if self.cover_image:
            return self.cover_image
        
        # 如果没有指定封面，使用第一页作为封面
        first_page = self.get_first_page()
        if first_page:
            return first_page.image_path
        
        return ""
    
    def update_stats(self):
        """更新统计信息"""
        self.total_chapters = len(self.chapters)
        self.total_pages = sum(chapter.page_count for chapter in self.chapters)
    
    def to_dict(self) -> dict:
        """转换为字典"""
        return {
            'id': self.id,
            'title': self.title,
            'path': self.path,
            'cover_image': self.get_cover_image(),
            'chapters': [chapter.to_dict() for chapter in self.chapters],
            'created_at': self.created_at.isoformat() if self.created_at else None,
            'updated_at': self.updated_at.isoformat() if self.updated_at else None,
            'total_chapters': self.total_chapters,
            'total_pages': self.total_pages
        }
    
    def to_summary_dict(self) -> dict:
        """转换为摘要字典（不包含页面详情）"""
        return {
            'id': self.id,
            'title': self.title,
            'path': self.path,
            'cover_image': self.get_cover_image(),
            'total_chapters': self.total_chapters,
            'total_pages': self.total_pages,
            'created_at': self.created_at.isoformat() if self.created_at else None,
            'updated_at': self.updated_at.isoformat() if self.updated_at else None
        }

class ComicLibrary:
    """漫画库管理类"""
    
    def __init__(self):
        self.comics: List[Comic] = []
        self._comic_index = {}  # ID到Comic的索引
    
    def add_comic(self, comic: Comic):
        """添加漫画"""
        self.comics.append(comic)
        self._comic_index[comic.id] = comic
    
    def get_comic(self, comic_id: str) -> Optional[Comic]:
        """获取指定漫画"""
        return self._comic_index.get(comic_id)
    
    def get_comics(self, page: int = 1, limit: int = 20) -> tuple[List[Comic], int]:
        """分页获取漫画列表"""
        start = (page - 1) * limit
        end = start + limit
        total = len(self.comics)
        
        return self.comics[start:end], total
    
    def search_comics(self, query: str) -> List[Comic]:
        """搜索漫画"""
        query = query.lower()
        results = []
        
        for comic in self.comics:
            if query in comic.title.lower():
                results.append(comic)
        
        return results
    
    def clear(self):
        """清空漫画库"""
        self.comics.clear()
        self._comic_index.clear()
    
    def rebuild_index(self):
        """重建索引"""
        self._comic_index.clear()
        for comic in self.comics:
            self._comic_index[comic.id] = comic